package com.nuvsoft.android.nuvgamenet;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Random;

public class GameNetHelpers {
	private static Random rand = new Random(System.currentTimeMillis());
	private static final int MIN_PORT = 49152;
	private static final int MAX_PORT = 65535;

	public static int getRandomPort() {
		int port;
		do {
			port = rand.nextInt(MAX_PORT - MIN_PORT) + MIN_PORT;
		} while (!isPortAvailable(port));
		return port;
	}

	private static boolean isPortAvailable(int port) {
		try {
			ServerSocket srv = new ServerSocket(port);
			srv.close();
			srv = null;
			return true;
		} catch (IOException e) {
			return false;
		}
	}
}
